package Thread;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;   
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.SocketException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.JOptionPane;

import org.apache.commons.net.ftp.FTPClient; 
/**
 * 
 * 下载线程类
 * @author 张雨
 * 
 */
public class DownloadThread extends Thread{   
	private String downloadFrom=null;
	private File fileDownloadTo=null;
	private long begin=0; 
	private long end=0;
	private Lock myLock=new ReentrantLock();

	/**
	 * 构造方法
	 * @param downloadFrom:FTP文件，String类型，eg:"\\ftp\\a.txt"
	 * @param fileDownloadTo：本地文件，File类型，eg:new File("c:\\ftp\\b.txt")
	 * @param begin:第一个字节的index
	 * @param end：最后一个字节的index
	 */
	DownloadThread(String downloadFrom,File fileDownloadTo,long begin,long end){
		this.downloadFrom=downloadFrom;
		this.fileDownloadTo=fileDownloadTo;
		this.begin=begin;
		this.end=end;
	}

	 public void run() {   
		 end++;
		 FTPClient client=new Client().getClient(); // 每个线程创建一个ftp用户
		 try {
			 //.......................下载指定字节块....................
			client.setRestartOffset(begin);
			byte[] buffer = new byte[1024];
			InputStream in = client.retrieveFileStream(downloadFrom);
			BufferedInputStream bufferIn = new BufferedInputStream(in);
			RandomAccessFile out = new RandomAccessFile(fileDownloadTo,"rw");  
			out.seek(fileDownloadTo.length());
			int len;
			long count=begin;
            while ((len = bufferIn.read(buffer))!=-1) {
            	if((count+len)<=end+1){
                     out.write(buffer, 0, len);
                     count+=len;
            	}
            	else{
            		out.write(buffer, 0, (int)(end-count));
            		break;
            	} 
            }
            in.close();
            out.close();
            client.disconnect();
            //...............未完成的线程数减一........................
            myLock.lock();
            UndoneDownloadThread.reduceUndoneThreadNum();
            myLock.unlock();
            //.......如果本线程是最后一个下载线程，则由本线程做最后的字节块拼接工作............
            if(UndoneDownloadThread.undoneThreadNum==0){
            	String localDir=DownloadPane.d.getText();
            	String temp=DownloadPane.b.getText();	
        		String localName=temp.substring(temp.lastIndexOf("\\")+1);
        		File local=new File(localDir+localName);
        		local.createNewFile();
        		RandomAccessFile localfile=new RandomAccessFile(local,"rw");
        		int i=0;
        		File f=null;
        		byte[] buf=new byte[1024];
        		while((f=new File(localDir+localName+" part"+(++i)+".temp")).exists()) {
        			BufferedInputStream tempbufferIn = new BufferedInputStream(new FileInputStream(f));
        			int length;
        			while((length=tempbufferIn.read(buf))!=-1){
        				localfile.write(buf, 0, length);
        			}
        			tempbufferIn.close();
        			f.delete();
        		}  
        		JOptionPane.showMessageDialog(null, "        恭喜，下载成功！");
            }
        
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	 }
	 
}